package com.bq.gametrade.ui.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bq.gametrade.HttpLink;
import com.bq.gametrade.R;
import com.bq.gametrade.base.BaseFragment;
import com.bq.gametrade.bean.UpdateUserInfo;
import com.bq.gametrade.bean.UpdateUserInfoDetails;
import com.bq.gametrade.http.VRHttp;
import com.bq.gametrade.http.VRHttpListener;
import com.bq.gametrade.ui.activity.BankCardListActivity;
import com.bq.gametrade.ui.activity.CancelledRecordedActivity;
import com.bq.gametrade.ui.activity.InterconnectedDetailsListActivity;
import com.bq.gametrade.ui.activity.LocationActivity;
import com.bq.gametrade.ui.activity.LoginActivity;
import com.bq.gametrade.ui.activity.MainActivity;
import com.bq.gametrade.ui.activity.PersonalDataActivity;
import com.bq.gametrade.ui.activity.PlatformInterconnectedActivity;
import com.bq.gametrade.ui.activity.RechargeActivity;
import com.bq.gametrade.ui.activity.RetrievePasswordActivity;
import com.bq.gametrade.ui.activity.SetPayPasswordActivity;
import com.bq.gametrade.ui.activity.SettingActivity;
import com.bq.gametrade.ui.activity.TransferActivity;
import com.bq.gametrade.ui.activity.WithdrawalActivity;
import com.bq.gametrade.utils.Base64Util;
import com.bq.gametrade.utils.SharedPreferencesUtils;
import com.bq.gametrade.utils.ToastUtils;
import com.bq.gametrade.widget.PromptAlertDialog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Feel on 2016/11/24 15:28
 */

public class MyAccountFragment extends BaseFragment implements View.OnClickListener{

    private SwipeRefreshLayout swipeRefreshLayout;
    private ImageView ivService;
    private MainActivity activity;
    private ImageView ivHadPortrait;
    private TextView tvUserName,tvBQAccount,tvBalanceMoney,tvGameTicket;
    private LinearLayout layTransfer,layTopUp,layWithdrawal,layPlatformContact,layTransferDetails,layBlankCard,layCancelledRecorded;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = (MainActivity)getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_my_account,container,false);
        initView(root);
        initSwipeRefresh(root);
        setPayPassword();
        return root;
    }


    private void initView(View view){
        ivService = (ImageView)view.findViewById(R.id.iv_userService);
        ivService.setOnClickListener(this);
        ivHadPortrait = (ImageView) view.findViewById(R.id.iv_headPortrait);
        ivHadPortrait.setOnClickListener(this);
        tvUserName = (TextView) view.findViewById(R.id.tv_userName);
        tvBQAccount= (TextView) view.findViewById(R.id.tv_bqAccount);
        tvBalanceMoney = (TextView) view.findViewById(R.id.tv_balanceMoney);
        tvGameTicket = (TextView) view.findViewById(R.id.tv_gameTicket);

        layTransfer = (LinearLayout) view.findViewById(R.id.lay_transfer);
        layTransfer.setOnClickListener(this);
        layTransfer.setVisibility(View.GONE);
        layTopUp = (LinearLayout) view.findViewById(R.id.lay_topUp);
        layTopUp.setOnClickListener(this);
        layWithdrawal = (LinearLayout) view.findViewById(R.id.lay_withdrawal);
        layWithdrawal.setOnClickListener(this);
        layPlatformContact = (LinearLayout) view.findViewById(R.id.lay_platformContact);
        layPlatformContact.setOnClickListener(this);
        layTransferDetails = (LinearLayout) view.findViewById(R.id.lay_transferDetails);
        layTransferDetails.setOnClickListener(this);
        layBlankCard = (LinearLayout) view.findViewById(R.id.lay_bankCard);
        layBlankCard.setOnClickListener(this);
        layCancelledRecorded = (LinearLayout) view.findViewById(R.id.lay_cancelledRecorded);
        layCancelledRecorded.setOnClickListener(this);
    }

    private void initSwipeRefresh(View view){
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipRefresh);

        //改变加载显示的颜色
        swipeRefreshLayout.setColorSchemeColors(
                Color.RED,
                R.color.color_finger_on,
                R.color.invest_rate_nomal,
                R.color.btn_green
        );
        //设置背景颜色
//        swipeRefreshLayout.setBackgroundColor(Color.YELLOW);
        //设置初始时的大小
        swipeRefreshLayout.setSize(SwipeRefreshLayout.LARGE);
        //设置监听
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getUserInfo();
            }
        });
        //设置向下拉多少出现刷新
        swipeRefreshLayout.setDistanceToTriggerSync(100);
        //设置刷新出现的位置
        swipeRefreshLayout.setProgressViewEndTarget(false, 200);
    }


    @Override
    public void onResume() {
        super.onResume();
        if(application.isLogin()){
            getUserInfo();
            setViewData();
        }
    }

    private void setViewData(){
        Glide.with(getActivity()).load(application.getUserInfo().headimg).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).error(R.mipmap.user_headimg_gray).into(ivHadPortrait);

        tvBQAccount.setText("比奇账号："+application.getUserInfo().bqAccount);
    }


    private void setPayPassword(){
        if(application.isLogin()){
            if(application.getUserInfo().pay_pass.equals("0")){
                new PromptAlertDialog(getActivity()).builder().setTitle("提示").setTouchOutsideCanceled(false)
                        .setMsg("您还没有设置支付密码？现在去设置")
                        .setPositiveButton("去设置", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(new Intent(getActivity(), SetPayPasswordActivity.class));
                            }
                        }).setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).show();
            }

        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser && isVisible()){
            if(application.isLogin()){

            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_userService:
               startActivity(new Intent(getActivity(),SettingActivity.class));
                break;
            case R.id.iv_headPortrait:
                startActivity(new Intent(activity, PersonalDataActivity.class));
                break;
            //提现
            case R.id.lay_withdrawal:
                startActivity(new Intent(activity, WithdrawalActivity.class));
                break;
            //充值
            case R.id.lay_topUp:
                startActivity(new Intent(activity, RechargeActivity.class));
                break;
            //转账
            case R.id.lay_transfer:

                startActivity(new Intent(getActivity(),TransferActivity.class));
                break;
            //平台互联
            case R.id.lay_platformContact:
                startActivity(new Intent(activity, PlatformInterconnectedActivity.class));
                break;
            //互联明细
            case R.id.lay_transferDetails:
                startActivity(new Intent(activity, InterconnectedDetailsListActivity.class));
                break;
            //银行卡管理
            case R.id.lay_bankCard:
                startActivity(new Intent(activity, BankCardListActivity.class));
                break;
            //挂单记录
            case R.id.lay_cancelledRecorded:
                startActivity(new Intent(activity, CancelledRecordedActivity.class));
                break;
        }
    }



    private void getUserInfo(){
        Map<String, String> params = new HashMap<>();
        params.put("token",application.getUserInfo().token);
        showSpotsDialog();
        VRHttp.updateUserInfo(getContext(), HttpLink.GET_USERINFO_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                closeSpotsDialog();
                UpdateUserInfo userInfo = (UpdateUserInfo) response;
                if(userInfo.status.equals("0")){
                    UpdateUserInfoDetails userInfoDetails = userInfo.userinfo;
                    application.getUserInfo().account = userInfoDetails.account;
                    application.getUserInfo().nickname = new  String(Base64.decode(userInfoDetails.nickname.getBytes(),0,userInfoDetails.nickname.length(),Base64.DEFAULT));
                    application.getUserInfo().telNum = userInfoDetails.telNum;
                    application.getUserInfo().userCard = userInfoDetails.userCard;
                    application.getUserInfo().userMoney = userInfoDetails.userMoney;
                    if(!application.getUserInfo().nickname.equals("")){
                        tvUserName.setText(application.getUserInfo().nickname);
                    }else {
                        tvUserName.setText("还没有昵称");
                    }
                    tvBalanceMoney.setText(application.getUserInfo().userMoney);
                    tvGameTicket.setText(application.getUserInfo().userCard);
                    tvBQAccount.setText("比奇账号："+userInfoDetails.bqAccount);


                }else if(userInfo.status.equals("99")){
                    ToastUtils.showToast(getActivity(),"登录超时请重新登陆");
                    application.setUserInfo(null);
                    startActivity(new Intent(getActivity(),LoginActivity.class));
                }else if(userInfo.status.equals("98")){
                    application.setUserInfo(null);
                    new PromptAlertDialog(getActivity()).builder().setTitle("提示").setTouchOutsideCanceled(true)
                            .setMsg("您的账号已在其他设备登录，如果不人本人登录请及时修改密码")
                            .setPositiveButton("修改密码", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    startActivity(new Intent(getActivity(), RetrievePasswordActivity.class));
                                }
                            }).setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startActivity(new Intent(getActivity(),LoginActivity.class));
                        }
                    }).show();

                }

            }

            @Override
            public void onFinish() {
                super.onFinish();
                swipeRefreshLayout.setRefreshing(false);
                closeSpotsDialog();
                boolean isGetAddress = (boolean)SharedPreferencesUtils.getValue(getActivity(),SharedPreferencesUtils.get_address,false);
                if(!isGetAddress){
                    initGps();
                }

            }
        });
    }

    private LocationClient locationClient = null;


    private void initGps() {
        LocationManager locationManager = (LocationManager) getActivity()
                .getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager
                .isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {

            AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
            dialog.setMessage("比奇交易需要临时获取您的位置,请打开GPS");
            dialog.setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {

                            // 转到手机设置界面，用户设置GPS
                            Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, 0); // 设置完成后返回到原来的界面

                        }
                    });
            dialog.setNeutralButton("取消", new android.content.DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    arg0.dismiss();
                }
            } );
            dialog.show();
        } else {
            try{
                MyLocationListenner myListener = new MyLocationListenner();
                locationClient = new LocationClient(getActivity());
                locationClient.registerLocationListener(myListener);
                LocationClientOption option = new LocationClientOption();
                option.setOpenGps(true);
//            option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
                option.setCoorType("bd09ll");
                option.setScanSpan(5000);
                option.disableCache(true);
                option.setIsNeedAddress(true);

                option.setPriority(LocationClientOption.NetWorkFirst);
                locationClient.setLocOption(option);
                locationClient.start();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    class MyLocationListenner implements BDLocationListener{
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null)
                return;
            StringBuffer sb = new StringBuffer(256);
            if (location.getLocType() == BDLocation.TypeGpsLocation) {
//				sb.append(location.getAddrStr());
                sb.append(location.getCity());
            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
                sb.append(location.getCity());
            }
            if (sb.toString() != null && sb.toString().length() > 0) {

            sendAddress(location.getAddrStr(),location.getCity());
            }

        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }
    }

    private void sendAddress(String address,String city){
        Map<String,String> params = new HashMap<>();
        params.put("token",application.getUserInfo().token);
        params.put("address", Base64Util.encode(address.getBytes()));
        params.put("city",Base64Util.encode(city.getBytes()));
        VRHttp.sendRequest(getActivity(), HttpLink.SEND_ADDRESS, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {

            }

            @Override
            public void onFinish() {
                super.onFinish();
                SharedPreferencesUtils.saveValue(getActivity(),SharedPreferencesUtils.get_address,true);
                if(locationClient != null){
                    locationClient.stop();
                }

            }
        });
    }

    @Override
    public void onStop() {
        super.onStop();
        if(locationClient != null){
            locationClient.stop();
        }
    }
}
